package com.work.music.interceptor;


import com.alibaba.fastjson.JSON;
import com.work.music.common.HttpRequestParamter;
import com.work.music.common.RedisSession;
import com.work.music.common.ResponseJson;
import com.work.music.exception.AjaxOperationFailException;
import com.work.music.utils.ContextUtil;
import com.work.music.utils.StringUtil;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AppLoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisSession redisSession;

    private List<String> executorList = new ArrayList<>();   //存储不需验证登陆的接口地址

    {
        executorList.add("/getPhoneCode");
        executorList.add("/login");
        executorList.add("/register");
        executorList.add("/uploadimg");
        executorList.add("/getSearchInfo");
        executorList.add("/getHomePage");
        executorList.add("/getLyricsById");
        executorList.add("/getSongsterInfo");
        executorList.add("/getAlbumInfo");
        executorList.add("/getLyricsBySongsterIdAndType");
        executorList.add("/getLyricsByAlbumId");  //
        executorList.add("/addWord");  //添加单词
        executorList.add("/getWordByName");
        executorList.add("/forgetPwd");  //忘记密码
    }

    public boolean isContains(String url) {
        boolean flag = false;
        for (String str : executorList) {
            if (url.contains(str)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
        String token = HttpRequestParamter.getToken();
        String url = req.getRequestURI();
        if (StringUtil.isNull(token)) {
            if (!isContains(url)) {
                writeJsonOutput(resp, 0);
                return false;
            }
        } else {
            if (redisSession == null) {//解决service为null无法注入问题
                BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext());
                redisSession = (RedisSession) factory.getBean("redisSession");
            }
            Map<String, Object> user = redisSession.getMapValue(token, 10, TimeUnit.DAYS);
            if (user == null || user.size() <= 0) {
                if (!isContains(url)) {
                    writeJsonOutput(resp, 0);
                    return false;
                }
            }
            if (user != null) {
                long uid = Long.parseLong(user.get("uid") + "");
                ContextUtil.setAttribute("uid", uid);
            }
        }
        return true;
    }

    private void writeJsonOutput(HttpServletResponse resp, int type) throws IOException {
        ResponseJson responseResult = new ResponseJson();
        if (type == 0) {
            responseResult.setStatus(101);
            responseResult.setMsg("请登录后再操作！");
            responseResult.setObj(ContextUtil.getBaseUrl());
        } else {
            responseResult.setStatus(102);
            responseResult.setMsg("对不起，您没有权限进行此操作！");
            responseResult.setObj(ContextUtil.getBaseUrl());
        }

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");

        resp.getWriter().write(JSON.toJSONString(responseResult));
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
